import 'package:flutter/material.dart';

import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/I10n/translations.dart';
import 'package:sainbainu/common/services/ali_oss.dart';
import 'package:sainbainu/common/services/app.dart';
import 'package:sainbainu/common/services/jpush.dart';

import 'package:sainbainu/common/services/user.dart';
import 'package:sainbainu/common/routes/router.dart';
import 'package:sainbainu/common/routes/routes.dart';
import 'package:sainbainu/common/services/wechat.dart';

import 'package:sainbainu/common/values/theme.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'common/services/jverify.dart';
import 'common/services/storage.dart';
import 'common/utils/easy_refresh.dart';
import 'common/utils/loading.dart';

void main() async {
  /// 使闪屏页保留在屏幕
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);

  /// runApp() 之前进行异步操作 必须调用这个
  WidgetsFlutterBinding.ensureInitialized();

  /// 移步初始化存储服务
  await Get.putAsync<StorageService>(() => StorageService().init());

  /// 初始化app配置
  Get.put<AppService>(AppService());

  /// 初始化用户配置
  Get.put<UserService>(UserService());

  /// 初始化智能认证
  Get.put<JverifyService>(JverifyService());

  /// 极光推送
  Get.put<JpushService>(JpushService());

  /// 微信 SDK
  Get.put<WechatService>(WechatService());

  /// 阿里 OSS
  Get.put<AliOssService>(AliOssService());

  runApp(const MyApp());

  /// 移除闪屏页
  FlutterNativeSplash.remove();
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    /// 初始化 EasyLoading 配置
    LoadingUtil.init();

    /// 初始化 EasyRefresh 配置
    EasyRefreshUtil();

    /// app 语言
    Locale? locale = Get.deviceLocale;
    if (AppService.to.locale != null) {
      locale = AppService.to.locale;
    }

    /// 默认页面
    String initialRoute;
    if (AppService.to.isFirstOpenApp) {
      initialRoute = AppRoutes.welcome;
    } else {
      initialRoute = AppRoutes.layout;
    }

    return GetMaterialApp(
      title: 'SainBainu',
      theme: appTheme,
      debugShowCheckedModeBanner: false,
      translations: AppTranslations(),
      supportedLocales: AppTranslations.supportedLocales, // 支持的语言字典
      locale: locale, // 设置初始语言为设备语言
      fallbackLocale: AppTranslations.fallbackLocale, // 设备语言不支持，使用这个
      localizationsDelegates:
          AppTranslations.localizationsDelegates, // 支持的组件或平台组件代理
      initialRoute: initialRoute,
      unknownRoute: AppRouter.unknownPage,
      getPages: AppRouter.getPages,
      builder: EasyLoading.init(),
    );
  }
}
